/**
 * 
 */
package com.pactera.android.version;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.pactera.android.R;
import com.pactera.android.model.VersionInfo;

/**
 * @author David Zheng
 *
 */
public class UpdateManager implements Runnable {
	
	static final String TAG = "UpdateManager";
	
	static final int NO_UPDATE = 0;
	
	static final int UPDATA_CLIENT = 1;
	
	static final int GET_UNDATAINFO_ERROR = 2;
	
	static final int DOWN_ERROR = 3;
	
	private Context context;
	
	private VersionInfo newVersionInfo;
	
	Message msg = new Message();
	
	//need spring to fix this ugly code
	private DownloadManager downloadManager = new DownloadManager(); 
	
	public UpdateManager(){
		
	}
	
	public UpdateManager(Context context) {
		this.context = context;
	}
	
	
	public void run() {
		try {			
			String path = context.getResources().getString(R.string.app_update_xml_url);
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			InputStream is = conn.getInputStream();
			newVersionInfo = downloadManager.getUpdataInfo(is);

			if (newVersionInfo.getVersion().equals(getCurrentVersionName())) {
				msg.what = UpdateManager.NO_UPDATE;
			} else {
				msg.what = UpdateManager.UPDATA_CLIENT;
			}
		} catch (Exception e) {
			msg.what = UpdateManager.GET_UNDATAINFO_ERROR;
		} finally {			 
			updateHandler.sendMessage(msg);
		}
	}
	
	
				
	Handler updateHandler = new Handler(){  
	      	    
		@Override  
	    public void handleMessage(Message msg) {  
	        super.handleMessage(msg);  
	        switch (msg.what) {
	        case NO_UPDATE:
	        	Toast.makeText(context, "The new version is not detected", Toast.LENGTH_SHORT).show();
	        	break;
	        
	        case UPDATA_CLIENT:  	               
	            showUpdataDialog();  
	            break;  
	        
	        case GET_UNDATAINFO_ERROR:  	               
	            Toast.makeText(context, "Failed to connect to the server, please try it later", Toast.LENGTH_LONG).show();  
	            //finish();  
	            break;    
	        
	        case DOWN_ERROR:  	              
	            Toast.makeText(context, "Failed to download the version, please try it later.", Toast.LENGTH_LONG).show();  
	            //finish();  
	            break;    
	        }  
	    }  
	};
			
	
	/**
	 * Show the update dialog;
	 */
	private void showUpdataDialog() {  
	    AlertDialog.Builder builer = new Builder(context) ;   
	    builer.setTitle("Update Available");  
	    builer.setMessage(newVersionInfo.getDescription());  	       
	    builer.setPositiveButton("Update", new OnClickListener() {  
	    public void onClick(DialogInterface dialog, int which) {  
	            Log.d(TAG, "download apk, updating");  
	            downLoadApk();  
	        }     
	    });  
	      
	    builer.setNegativeButton("Cancel", new OnClickListener() {  
	        public void onClick(DialogInterface dialog, int which) {  	             
	        	dialog.dismiss();        
	        }  
	    });  
	    
	    AlertDialog dialog = builer.create();  
	    dialog.show();  
	}
	
	
	/**
	 * downloads the apk and shows the progress bar.
	 */
	private void downLoadApk() {  
	    final ProgressDialog pd = new  ProgressDialog(context);  
	    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
	    pd.setMessage("Downloading...");  
	    pd.show();  
	    new Thread(){  
	        @Override  
	        public void run() {  
	            try {
	            	downloadManager.setContext(context);
	                File file = downloadManager.getFileFromServer(newVersionInfo.getUrl(), pd);  
	                //sleep(2500);  
	                installApk(file); 
	                pd.dismiss();
	            } catch (Exception e) {  
	                Message msg = new Message();  
	                msg.what = DOWN_ERROR;  
	                updateHandler.sendMessage(msg);  	                
	            } finally {
	            	//pd.dismiss();
	            }
	        }}.start();  
	}  
	
	
	
	/**
	 * Install the apk
	 * @param file
	 */
	private void installApk(File apkfile) { 		  
        if (!apkfile.exists()) {  
            return;  
        }  
	    Intent intent = new Intent();  	      
	    intent.setAction(Intent.ACTION_VIEW);  	      
	    intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");  
	    context.startActivity(intent);  
	}  
	
	/**
	 * Gets the current version name
	 * @return
	 * @throws Exception
	 */
	private String getCurrentVersionName() throws Exception{
		PackageManager packageManager = context.getPackageManager();
	    // "0" means to get the version
		PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
		
	    return packInfo.versionName; 
	}
			
	/**
	 * @param context the context to set
	 */
	public void setContext(Context context) {
		this.context = context;
	}
	
	
	

}
